#include <avr/io.h>
#include <inttypes.h>
#include <util/delay.h>
#include <inttypes.h>
#include <stdlib.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
//#include "pwm.h"

#define step1 0x01
#define step2 0x02
#define step3 0x04
#define step4 0x08
#define MOTOR_DDR DDRC

unsigned char motion_table[]={step1,step2,step3,step4};

unsigned char step;

/*

		(PORTD2-second)          (PORTD4-fourth)
		           (O)
		   
            (PORTD 1-first)   (PORTD3-third)	
				   TOP VIEW

*/


unsigned char gl_count;
volatile unsigned char counter_pwm;

void Delay(int msec){ 

	int i=0;
		for(i=0;i<msec;i++) _delay_ms(1);
	
}



void full_step_ccw(unsigned char count, unsigned char dly)
{

	while(count--)
	{
		
	PORTC=0b0001000;
	Delay(dly);
	PORTC=0b00000010;
	Delay(dly);
	PORTC=0b00000100;
	Delay(dly);
	PORTC=0b00000001;
	Delay(dly);
	}
}

void full_step_cw(unsigned char count,unsigned char dly)
{

	while(count--)
	{
	
	PORTC=0b00000001;
	Delay(dly);
	PORTC=0b00000010;
	Delay(dly);
	PORTC=0b00000100;
	Delay(dly);
	PORTC=0b00001000;
	Delay(dly);	
	gl_count++;
	
	
	}
}
ISR (INT2_vect) 
{
}
ISR (INT1_vect) 
{
    SREG = 0;
	
	//full_step_ccw(gl_count,5);
	
		if(step == 4) step=0;
		PORTC = motion_table[step++];
		Delay(300);
	
    SREG |= 0x80;
}
ISR (INT0_vect) 
{
   SREG = 0;
	
    full_step_cw(gl_count,5);
    SREG |= 0x80;
}


void interrupt_init(void){
  SREG = 0;
    GICR = 0;
    GICR &= 0xDF;
   // GIFR |= (1<<INTF2)|(1<<INTF1)|(1<<INTF0);
   // GICR |= (1<<INT2)|(1<<INT1)|(1<<INT0);
    GIFR |= (1<<INTF1)|(1<<INTF0);
	GICR |= (1<<INT1)|(1<<INT0);
    SREG |= 0x80;

}



int main(void){
	
	char i=0;
	unsigned char count=0;
	DDRD=0xff;
	PORTD=0x00;
    while(1)
	{
	
	i=0;
	for(count=0;count<100;count++)
	{
		if(i==4) i=0;
		PORTD = motion_table[i];
		i++;
		Delay(5);
	}
	
	i=3;
	
	for(count=0;count<100;count++)
	{
		PORTD = motion_table[i];
		i--;
		if(i<0) i=3;
		Delay(5);
	}
	
    }
    return 0;
}
